package ch.ffhs.links_library.session;

import java.security.MessageDigest;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.log.Log;
import org.jboss.seam.international.StatusMessages;

import ch.ffhs.links_library.entities.User;

@Stateless
@Name("register")
public class RegisterBean implements Register
{
    @Logger private Log log;

    @In StatusMessages statusMessages;

    /* DB Context to store user */
	@PersistenceContext
	private EntityManager em;
	
	/**
	 * User object for a newly registered user
	 */
	@Out(required=false, scope=ScopeType.PAGE)
	private User newUser;
	
	
	public String createUser() {
		log.info("User Object created");
		newUser = new User();
		return "register";
	}
	
    public String register()
    {   
    	//FIXME: Encryption
        try {
        	em.persist(newUser);
        	log.info("User " + newUser.getUsername() + " persisted");
        	statusMessages.add("User registered");
        } catch(Exception e) {
        	log.error("Error writing new user to database");
        	statusMessages.add(org.jboss.seam.international.StatusMessage.Severity.ERROR, "Error registering user, please try again");
        }
        
        return "login";
        
    }

}
